package com.kirayous.api.strategy.factory;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.collect.Maps;
import com.kirayous.api.strategy.UploadStrategy;
import com.kirayous.common.enums.UploadModeEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * @author KiraYous
 * @version V1.0
 * @Package com.kirayous.api.strategy.factory
 * @date 2021/10/25 20:20
 */
@Component
public class UploadStrategyFactory {


    /**
     * 上传模式
     *
     * @Value 让该类成为spring的bean才能起效
     */
//    @Value("${upload.mode}") 这里不能使用@Value 直接修饰static 变量，直接修饰不起效
    private static String uploadMode;

    @Value("${upload.mode}") //set方法也不能被static修饰，凡是对于final static修饰的，@Value都不起效
    public void setUploadMode(String uploadMode){
        UploadStrategyFactory.uploadMode=uploadMode;
    }

///    @Autowired  实际上如果使用 @Autowired springboot会自动帮你去找UploadStrategy相关的实现内容，但是这会出现一种轮询
    //所以还是建议使用自定义工厂方法
    private static final Map<String, UploadStrategy> uploadStrategyMap= Maps.newHashMap();

    /**
     * 上传文件
     *
     * @param file 文件
     * @param path 路径
     * @return {@link String} 文件地址
     */
    public static String executeUploadStrategy(MultipartFile file, String path) {

//        System.out.println("uploadMode:  "+uploadMode);
        return getInvokeStrategy(uploadMode).uploadFile(file, path);
    }

    /**
     *
     * @param name
     * @return UploadStrategy
     *
     */
    public static UploadStrategy getInvokeStrategy(String name){
        return uploadStrategyMap.get(UploadModeEnum.getStrategy(name));
    }
    public static void register(String name,UploadStrategy strategy){
        if(StringUtils.isBlank(name)||null==strategy){
            return;
        }
        uploadStrategyMap.put(name,strategy);
    }


}
